from selenium import webdriver
import pytest
import os
import yaml
from model.application import Application
from model.user import User


def pytest_addoption(parser):
    parser.addoption("--browser", action="store", default="firefox", help="browser type")
    parser.addoption("--base_url", action="store", default="http://localhost/php4dvd/", help="base URL")


@pytest.fixture(scope="session")
def browser_type(request):
    return request.config.getoption("--browser")


@pytest.fixture(scope="session")
def base_url(request):
    return request.config.getoption("--base_url")


@pytest.fixture(scope="session")
def app(request, browser_type, base_url):
    if browser_type == "firefox":
        driver = webdriver.Firefox()
    elif browser_type == "chrome":
        driver = webdriver.Chrome()
    elif browser_type == "ie":
        driver = webdriver.Ie()
    request.addfinalizer(driver.quit)
    return Application(driver, base_url)


@pytest.fixture(scope='session', autouse=True)
def login(app):
    app.ensure_login_as(User.Admin())


#@pytest.fixture(scope='session', autouse=True)
def setup(request, cfg):
    global b

    b = webdriver.Firefox(
        capabilities={'unexpectedAlertBehaviour': 'accept'}
    )
    b.implicitly_wait(10)

    host = os.getenv('HOST', None)
    if host is None:
        host = cfg['wamp']['host']

    b.get('http://' + host + cfg['wamp']['url'])
    b.find_element_by_id('username').send_keys(cfg['user']['login'])
    b.find_element_by_name('password').send_keys(cfg['user']['password'])
    b.find_element_by_name('submit').click()

    def fin():
        b.quit()

    request.addfinalizer(fin)


#@pytest.fixture(scope='session')
def cfg():
    with open(os.path.dirname(os.path.realpath(__file__)) + '/config.yml', 'r') as f:
        doc = yaml.load(f)
    return doc


#@pytest.fixture(scope='session')
def browser():
    return b

